package com.java.web.util;

import java.io.File;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadUtils {
	
	/**
	 * 利用apache的文件库上传文件
	 * @Method: upload 
	 * @Description: TODO
	 * @param request
	 * @param path
	 * @return:void
	 */
	public static void  upload(HttpServletRequest request,String path){
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");//支持中文文件名
		try{
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = iter.next();
			    if (!item.isFormField()){
			       File pathFile=new File(path);
			       if(!pathFile.exists()){
			    	   pathFile.mkdirs();
			       }
			       String sourceFileAbsolutePath=item.getName();
			       //分隔符
			       String separator=File.separator;
			       String sourceFileName=sourceFileAbsolutePath.substring(sourceFileAbsolutePath.lastIndexOf(separator)+1);
			       File uploadedFile = new File(path+separator+sourceFileName);
			       item.write(uploadedFile);
			    }
			}
			
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
